package im.yisme.model.fileio;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class MusicCopy {

	private String path;
	
	public MusicCopy(){
		path = DirManager.getMusicDir();
		createPath();
	}
	
	private void createPath(){
		File file = new File(path);
		file.mkdirs();
	}
	
	public String copy(String src, long id) throws IOException{
		File target = new File(DirManager.getMusicDir() + id + ".mp3");
		
		BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {
        	InputStream is = null;
        	if (src.startsWith("http")){
        		URL url = new URL(src);
        		URLConnection connection = url.openConnection();
        		is = connection.getInputStream();
        	}
        	else{
        		is = new FileInputStream(src);
        	}
        	
            inBuff = new BufferedInputStream(is);
            outBuff = new BufferedOutputStream(new FileOutputStream(target));

            byte[] b = new byte[1024];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }

            outBuff.flush();
        } finally {
            if (inBuff != null)
                inBuff.close();
            if (outBuff != null)
                outBuff.close();
        }
        return target.getPath();
	}
}
